<template>
    <div class="login-box">

        <el-form style="max-width: 460px" :model="data" :rules="rules" ref="ruleFormRef">
            <div style="margin: 20px" />
            <el-form-item prop="username">
                <el-input class="w-50 m-2" placeholder="请输入用户名"  v-model="data.username" />
            </el-form-item>

            <el-form-item prop="userpass">
                <el-input class="w-50 m-2" placeholder="请输入密码"  v-model="data.userpass"
                  type="password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loginCheck(ruleFormRef)">登录</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {  reactive, ref, } from 'vue';
import type { FormInstance,ElMessage } from "element-plus";

import {loginCheckApi} from "@/api/admin"

// 双向绑定表单元素的数据
interface IData {
    username: string,
    userpass: string
}

const data = reactive<IData>({
    username: "admin",
    userpass: "123456"
})

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    userpass: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
})

let $router = useRouter();

const ruleFormRef = ref<FormInstance>()

function loginCheck(formEl: FormInstance | undefined) {
    // 1、判断用户的输入（非空判断，正则判断）
    console.log("ruleFormRef", ruleFormRef);

    if (!formEl) return
    
    formEl.validate((valid, fields) => {
        if (valid) {
            loginCheckApi({
                adminname:data.username,
                password:data.userpass
           })
           .then((res:any)=>{
                if(res.code==="200"){
                    ElMessage('登录成功！');
                    console.log("token",res.data.token);                    

                    localStorage.setItem("useranme",data.username);
                    // 保存token
                    localStorage.setItem("token",res.data.token);
                    // 跳转到首页
                    $router.push("/admin");
                    
                }else if(res.code==="10003"){
                    ElMessage('密码错误！')
                }else if(res.code==="10005"){
                    ElMessage('该用户名未注册！');
                }else{
                    ElMessage('这个提示一般不会出现！');
                }
            })
            .catch((err:any)=>{
                ElMessage('服务器出错！',err);
            })
        } else {
            console.log('error submit!', fields)
        }
    })

    
}

</script>

<style scoped>
.login-box {
    width: 100%;
    height: 100%;
    background: url(https://cas.1000phone.net/cas/images/login/bg.png) 50% no-repeat;
    background-size: cover;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.el-form {
    background-color: #fff;
    width: 400px;
    height: 200px;
    padding: 20px;
}
</style>